<template>
  <div class="real-app">
    <input type="text"
           placeholder="接下来要做什么?"
           autofocus="true"
           @keyup.enter="addTodo"
           class="add-input"
    >
    <item :todo="todo"
          v-for="todo in filteredTodos"
          :key="todo.id"
          @del="deleteTodo"
          @itemClick="itemClick(todo)"
    />
    <div style="background-color: white;text-align: center;padding: 10px" v-show="showPage">
      <Page :total="todoTotal" :pageSize="pageSize" @on-change="pageChange" :current="currentPage"/>
    </div>
    <Tabs :filter="filter" :todos="todos" @toggle="toggleFilter" @clearComplete="clearAllComplete"
          @selectTime="gettodosbytime"></Tabs>

  </div>
</template>

<style lang="stylus" scoped>
  .add-input {
    width 100%
    color inherit
    padding 16px 16px 16px 60px
    font-size 20px
    position relative
    border: none
    outline none
    margin 0
    font-family inherit
    font-weight inherit
    line-height 1.4em
    /*该属性可让padding 不影响宽高*/
    box-sizing border-box
    /*让文字卡起来清楚一些*/
    font-smoothing: antialiased;
    border-bottom 1px solid rgba(135, 178, 147, 0.4)
  }

  .real-app {
    background white
    width 600px
    margin 0 auto
    box-shadow 0 0 5px #666
  }
</style>

<script>
  import Item from './item.vue'
  import Tabs from './tabs.vue'
  import {getDay, getSimpleFormatDate} from '../utils/timeUtils'

  let id = 0
  export default {
    computed: {
      filteredTodos() {
        var finalList
        if (this.filter === '全部') {
          finalList = this.todos
        } else if (this.filter === '已完成') {
          finalList = this.todos.filter(todo => todo.completed)
        } else {
          finalList = this.todos.filter(todo => !todo.completed)
        }
        this.todoTotal = finalList.length
        if (this.todoTotal >= this.pageSize) {
          this.showPage = true
          //根据页码动态显示部分数据
          var start = (this.currentPage - 1) * this.pageSize
          var end = (this.currentPage) * this.pageSize

          finalList = finalList.slice(start, end)
          console.log("当前页：" + this.currentPage)
          console.log("开始：" + start + "   结束：" + end)
        } else {
          this.showPage = false
        }
        return finalList
      },


    },
    methods: {
      itemClick(todo) {
        var vm = this;
        this.$http.post('/v1/users/updateTodo', {
          token: this.token,
          userId: this.userid,
          todoId: todo.id,
          isOver: todo.completed ? 0 : 1
        }).then(function (response) {
          if (response.data.code === 1000) {
            console.log(todo.completed)
            if (todo.completed) {
              todo.completed = true
            } else {
              todo.completed = false
            }
            console.log(todo.completed)
          } else {
            vm.$Message.error(response.data.message)
            todo.completed = false
          }
        }).catch(function (e) {
          alert(e.message)
          todo.completed = false
        })

      },
      getTodoList() {
        var vm = this
        var startTime;
        var endTime;
        if (this.finalStartTime != 'all') {
          startTime = new Date(this.finalStartTime + ' 00:00:00').getTime()/1000
          endTime = new Date(this.finalEndTime + ' 23:59:59').getTime()/1000
        } else {
          startTime = ''
          endTime = ''
        }

        this.$http.get('/v1/users/todoList', {
          params: {
            token: this.token,
            userId: this.userid,
            start: startTime,
            end: endTime
          }
        })
          .then(function (response) {
            if (response.data.code === 1000) {
              var result = response.data.data.list
              vm.todos = []
              for (var i = 0; i < result.length; i++) {
                console.log("todoList:  " + result[i])
                vm.todos.unshift({
                  id: result[i].todoId,
                  content: result[i].content,
                  completed: result[i].isOver === 0 ? false : true
                })
              }
            } else {
              alert(response.data.message)
            }
          }).catch(function (e) {
          alert(e.message)
        })
      },
      addTodo(e) {
        var value = e.target.value.trim()
        if (value === "") {
          return
        }
        var vm = this;
        this.$http.post('/v1/users/saveTodo', {
          token: this.token,
          userId: this.userid,
          content: value
        }).then(function (response) {
          if (response.data.code === 1000) {
            console.log("saveTodo:  " + response.data.data)
            vm.getTodoList()
            vm.currentPage = 1
//            vm.todos.unshift({
//              id: todoId,
//              content: value,
//              completed: false
//            })
            e.target.value = ''
          } else {
            alert(response.data.Msg)
          }
        }).catch(function (e) {
          alert(e.message)
        })


      },
      deleteTodo(id) {
        var vm = this
        this.$http.post('/v1/users/delTodo', {
          token: this.token,
          userId: this.userid,
          todos: id
        }).then(function (res) {
          if (res.data.code === 1000) {
            vm.todos.splice(vm.todos.findIndex(todo => todo.id === id), 1)
          } else {
            vm.$Message.error(res.data.message)
          }
        })
      },
      toggleFilter(state) {
        this.filter = state
      },
      //清除所有已完成
      clearAllComplete() {
        var vm = this;
        var deletes = this.todos.filter(todo => todo.completed)
        var deleteStr = ""
        for (var i = 0; i < deletes.length; i++) {

          if (i == 0) {
            deleteStr = deletes[i].id
          } else {
            deleteStr = deleteStr + ',' + deletes[i].id
          }
        }
        this.$http.post('/v1/users/delTodo', {
          token: this.token,
          userId: this.userid,
          todos: deleteStr
        }).then(function (res) {
          if (res.data.code === 1000) {
            vm.getTodoList()
          } else {
            vm.$Message.error(res.data.message)
          }
        })
        // this.todos = this.todos.filter(todo => !todo.completed)
      },
      pageChange(result) {
        this.currentPage = result
      },
      gettodosbytime(start, end) {
        console.log(start)
        console.log(end)
        this.finalStartTime = start
        this.finalEndTime = end
        this.getTodoList()
      }
    },
    data() {
      return {
        todos: [],
        filter: '全部',
        token: '',
        userid: "",
        pageSize: 5,
        todoTotal: 0,
        currentPage: 1,
        showPage: false,
        finalStartTime: '',
        finalEndTime: "",
      }
    },
    created() {
      var userInfo = JSON.parse(localStorage.getItem("userInfo"))
      if (userInfo) {
        this.token = userInfo.token
        this.userid = userInfo.userId
        console.log(this.token)
        console.log(this.userid)
//        默认显示近三天的
        this.finalStartTime = getDay(-3)
        this.finalEndTime = getDay(0)
        this.getTodoList()
      } else {
        this.$router.push('/login')
      }
    },
    components: {
      Item,
      Tabs
    }
  }
</script>
